package com.kevin.utilits.curator.treecache;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.log4j.Logger;

import com.kevin.utilits.zookeeper.CuratorUtils;

public class TreeListenerTest {
	public static final String NAMESPACE = "TreeListenerTest";
	public static final String CHARSET = "UTF-8";
	private static Logger logger = Logger.getLogger(TreeListenerTest.class);

	public static void main(String[] args) {
		try {
			CuratorUtils.init("10.198.195.147:2181", 1000, 3, 1000, NAMESPACE);
			CuratorFramework client = CuratorUtils.getClient();

			TreeCache treeCache = new TreeCache(client, "/");
			treeCache.getListenable().addListener(new TreeCacheListener() {
				@Override
				public void childEvent(CuratorFramework client, TreeCacheEvent event){
					try{
						logger.info("------------------------------------------------------");
						if (TreeCacheEvent.Type.INITIALIZED.name().equals(event.getType().name())){
							logger.info(event.getType().name());
						}else if (TreeCacheEvent.Type.NODE_ADDED.name() .equals( event.getType().name())){
							logger.info(event.getType().name()+"_"+event.getData().getPath() +"_"+ new String(event.getData().getData()));
						}else if (TreeCacheEvent.Type.NODE_UPDATED.name().equals(event.getType().name())){
							logger.info(event.getType().name()+"_"+event.getData().getPath() +"_"+ new String(event.getData().getData()));
						}else if (TreeCacheEvent.Type.NODE_REMOVED.name().equals(event.getType().name())){
							logger.info(event.getType().name()+"_"+event.getData().getPath() );
						}else if (TreeCacheEvent.Type.CONNECTION_SUSPENDED.name().equals(event.getType().name())){
							logger.info(TreeCacheEvent.Type.CONNECTION_SUSPENDED);
						}else if (TreeCacheEvent.Type.CONNECTION_RECONNECTED.name().equals(event.getType().name())){
							logger.info(TreeCacheEvent.Type.CONNECTION_RECONNECTED);
						}else if (TreeCacheEvent.Type.CONNECTION_LOST.name().equals(event.getType().name())){
							logger.info(TreeCacheEvent.Type.CONNECTION_LOST);
						}
					}catch(Exception e){
						logger.error(e.getMessage(), e);
					}
				}
			});
			treeCache.start();
			
			Thread.sleep(Integer.MAX_VALUE);
			client.close();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
}